package com.example.compreshensiveshop.service.imp;

import cn.hutool.crypto.digest.DigestUtil;
import com.example.compreshensiveshop.common.JsonResponse;
import com.example.compreshensiveshop.dao.RoleDao;
import com.example.compreshensiveshop.dao.UserDao;
import com.example.compreshensiveshop.dao.UserRoleDao;
import com.example.compreshensiveshop.dto.LoginDTO;
import com.example.compreshensiveshop.dto.PasswordUpdateDTO;
import com.example.compreshensiveshop.dto.RegisterDTO;
import com.example.compreshensiveshop.po.*;
import com.example.compreshensiveshop.service.CustomerService;
import com.example.compreshensiveshop.service.SellerService;
import com.example.compreshensiveshop.service.UserService;
import com.example.compreshensiveshop.utils.JwtUtil;
import com.example.compreshensiveshop.vo.RoleVO;
import com.example.compreshensiveshop.vo.SellerLoginVO;
import com.example.compreshensiveshop.vo.SellerVO;
import com.example.compreshensiveshop.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;


/**
 * User Service Implementation
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private SellerService sellerService;

    @Override
    public JsonResponse<UserVO> login(LoginDTO loginDTO) {
        // 1. 根据用户名查询用户
        UserPO userPO = userDao.selectByUsername(loginDTO.getName());
        if (userPO == null) {
            return JsonResponse.failure("用户名或密码错误");
        }

        // 2. 验证密码（加密后对比）
        String inputPasswordEncrypted = DigestUtil.md5Hex(loginDTO.getPassword());
        if (!inputPasswordEncrypted.equals(userPO.getPassword())) {
            return JsonResponse.failure("用户名或密码错误");
        }

        // 3. 检查用户状态（0正常，1禁用）
        if (userPO.getStatus() == 1) {
            return JsonResponse.failure("账号已被禁用，请联系管理员");
        }

        // 4. 更新最后登录时间
        Timestamp now = new Timestamp(System.currentTimeMillis());
        userDao.updateLastLoginTime(userPO.getId(), now);
        userPO.setLastLoginTime(now); // 同步更新内存中的时间
        Long customerId =customerService.queryCustomerId(userPO.getId());
        Long sellerId =sellerService.querySellerId(userPO.getId());

        // 5. 查询用户角色信息
        List<UserRolePO> userRoles = userRoleDao.selectByUserId(userPO.getId());
        List<RoleVO> roleVOs = new ArrayList<>();
        if (userRoles != null && !userRoles.isEmpty()) {
            // 查询所有角色信息
            for (UserRolePO userRole : userRoles) {
                RolePO rolePO = roleDao.selectById(userRole.getRoleId());
                if (rolePO != null) {
                    if(rolePO.getCode().equals("CUSTOMER")){
                        RoleVO roleVO = new RoleVO();
                        roleVO.setId(customerId);
                        roleVO.setName(rolePO.getName());
                        roleVO.setCode(rolePO.getCode());
                        roleVOs.add(roleVO);
                    }
                    if (rolePO.getCode().equals("SELLER")){
                        RoleVO roleVO = new RoleVO();
                        roleVO.setId(sellerId);
                        roleVO.setName(rolePO.getName());
                        roleVO.setCode(rolePO.getCode());
                        roleVOs.add(roleVO);
                    }
                }
            }
        }

        String token = JwtUtil.generateJwt( userPO.getId(),customerId, sellerId);
        // 6. 转换为VO返回（隐藏密码等敏感信息）
        UserVO userVO = new UserVO();
        userVO.setRoles(roleVOs);
        userVO.setToken( token);

        return JsonResponse.success(userVO, "登录成功");
    }

    @Override
    @Transactional
    public JsonResponse<UserVO> register(RegisterDTO registerDTO) {
        // 1. 用户名密码验证
        // 手动验证用户名
        if (registerDTO.getName() == null || registerDTO.getName().trim().isEmpty()) {
            return JsonResponse.failure("用户名不能为空");
        }
        if (!registerDTO.getName().matches("^[a-zA-Z0-9]{4,9}$")) {
            return JsonResponse.failure("用户名只能包含数字和字母，长度为4-9位");
        }
        // 检查用户名是否已存在
        UserPO existingUser = userDao.selectByUsername(registerDTO.getName());
        if (existingUser != null) {
            return JsonResponse.failure("用户名已被占用");
        }
        // 验证密码
        if (registerDTO.getPassword() == null || registerDTO.getPassword().trim().isEmpty()) {
            return JsonResponse.failure("密码不能为空");
        }
        if (registerDTO.getPassword().length() < 6 || registerDTO.getPassword().length() > 10) {
            return JsonResponse.failure("密码长度必须为6-10位");
        }

        // 2. 手机号验证
        // 验证手机号
        if (registerDTO.getPhone() == null || registerDTO.getPhone().trim().isEmpty()) {
            return JsonResponse.failure("手机号不能为空");
        }
        if (!registerDTO.getPhone().matches("^1[3-9]\\d{9}$")) {
            return JsonResponse.failure("手机号格式不正确");
        }
        // 检查手机号是否已注册
        existingUser = userDao.selectByPhone(registerDTO.getPhone());
        if (existingUser != null) {
            return JsonResponse.failure("手机号已被注册");
        }

        // 3. 创建新用户
        UserPO newUser = new UserPO();
        newUser.setName(registerDTO.getName());
        newUser.setPassword(DigestUtil.md5Hex(registerDTO.getPassword()));// 密码加密
        newUser.setPhone(registerDTO.getPhone());
        newUser.setStatus(0); // 默认正常状态

        // 4. 插入数据库
        int result = userDao.insert(newUser);
        customerService.addCustomer(newUser.getId());
        if (result <= 0) {
            return JsonResponse.failure("注册失败");
        }

        // 5. 添加用户角色关联（默认角色ID为3）
        UserRolePO userRolePO = UserRolePO.builder()
                .userId(newUser.getId())
                .roleId(3L)
                .build();
        userRoleDao.addSellerRole(userRolePO);

        // 6. 构造返回结果
        UserVO userVO = new UserVO();


        // 7. 查询并设置角色信息
        List<RoleVO> roleVOs = new ArrayList<>();
        RolePO rolePO = roleDao.selectById(3L);
        if (rolePO != null) {
            RoleVO roleVO = new RoleVO();
            roleVO.setId(rolePO.getId());
            roleVO.setName(rolePO.getName());
            roleVO.setCode(rolePO.getCode());
            roleVOs.add(roleVO);
        }
        userVO.setRoles(roleVOs);

        return JsonResponse.success(userVO, "注册成功");
    }

    /*
    *商家登录
    **/
    @Override
    public JsonResponse<SellerLoginVO> sellerLogin(LoginDTO loginDTO) {
        // 1. 根据用户名查询用户
        UserPO userPO = userDao.selectByUsername(loginDTO.getName());
        if (userPO == null) {
            return JsonResponse.failure("用户名或密码错误");
        }

        // 2. 验证密码（（加密后对比））
        String inputPasswordEncrypted = DigestUtil.md5Hex(loginDTO.getPassword());
        if (!inputPasswordEncrypted.equals(userPO.getPassword())) {
            return JsonResponse.failure("用户名或密码错误");
        }

        // 3. 检查用户状态（0正常，1禁用）
        if (userPO.getStatus() == 1) {
            return JsonResponse.failure("账号已被禁用，请联系管理员");
        }

        // 4. 验证是否为商家角色
        List<UserRolePO> userRoles = userRoleDao.selectByUserId(userPO.getId());
        boolean isSeller = false;
        if (userRoles != null && !userRoles.isEmpty()) {
            for (UserRolePO userRole : userRoles) {
                // 角色ID为2的是商家角色
                if (userRole.getRoleId() == 2L) {
                    isSeller = true;
                    break;
                }
            }
        }

        if (!isSeller) {
            return JsonResponse.failure("您不是商家用户，无法登录商家系统");
        }

        // 5. 更新最后登录时间
        Timestamp now = new Timestamp(System.currentTimeMillis());
        userDao.updateLastLoginTime(userPO.getId(), now);
        userPO.setLastLoginTime(now); // 同步更新内存中的时间

        // 6. 获取sellerId
        Long sellerId = sellerService.querySellerId(userPO.getId());
        Long customerId = customerService.queryCustomerId(userPO.getId());
        SellerPO sellerPO = sellerService.queryById(sellerId);
        // 7. 查询用户角色信息
        List<RoleVO> roleVOs = new ArrayList<>();
        if (userRoles != null && !userRoles.isEmpty()) {
            for (UserRolePO userRole : userRoles) {
                RolePO rolePO = roleDao.selectById(userRole.getRoleId());
                if (rolePO != null) {
                    if (rolePO.getCode().equals("CUSTOMER")) {
                        RoleVO roleVO = new RoleVO();
                        roleVO.setId(customerId);
                        roleVO.setName(rolePO.getName());
                        roleVO.setCode(rolePO.getCode());
                        roleVOs.add(roleVO);
                    }
                    if (rolePO.getCode().equals("SELLER")) {
                        RoleVO roleVO = new RoleVO();
                        roleVO.setId(sellerId);
                        roleVO.setName(rolePO.getName());
                        roleVO.setCode(rolePO.getCode());
                        roleVOs.add(roleVO);
                    }
                }
            }
        }

        String token = JwtUtil.generateJwt(userPO.getId(), customerId, sellerId);
        // 8. 构造返回结果
        SellerLoginVO userVO = new SellerLoginVO();
        userVO.setRoles(roleVOs);
        userVO.setToken(token);
        if (sellerPO != null) {
            userVO.setShopName(sellerPO.getShopName());
            userVO.setLogoUrl(sellerPO.getLogoUrl());
        } else {
            userVO.setShopName("未设置店铺名称");
            userVO.setLogoUrl(""); // 或设置默认图片URL
        }
        return JsonResponse.success(userVO, "商家登录成功");
    }

    /*
    * 修改密码
    **/
    @Override
    public JsonResponse<UserVO> updatePassword(PasswordUpdateDTO passwordUpdateDTO) {
        if (passwordUpdateDTO == null) {
            return JsonResponse.failure("请求参数不能为空");
        }

        if (passwordUpdateDTO.getName() == null || passwordUpdateDTO.getName().trim().isEmpty()) {
            return JsonResponse.failure("用户名不能为空");
        }

        if (passwordUpdateDTO.getPhone() == null || passwordUpdateDTO.getPhone().trim().isEmpty()) {
            return JsonResponse.failure("手机号不能为空");
        }

        if (!passwordUpdateDTO.getPhone().matches("^1[3-9]\\d{9}$")) {
            return JsonResponse.failure("手机号格式不正确");
        }

        if (passwordUpdateDTO.getNewPassword() == null || passwordUpdateDTO.getNewPassword().trim().isEmpty()) {
            return JsonResponse.failure("新密码不能为空");
        }

        if (passwordUpdateDTO.getNewPassword().length() < 6 || passwordUpdateDTO.getNewPassword().length() > 10) {
            return JsonResponse.failure("新密码长度必须为6-10位");
        }

        try {
            JsonResponse<UserPO> userCheck = validateUser(passwordUpdateDTO.getName());
            if (!userCheck.isStatus()) {
                return JsonResponse.failure(userCheck.getMessage());
            }

            UserPO userPO = userCheck.getData();

            String phone = passwordUpdateDTO.getPhone();
            if (!phone.equals(userPO.getPhone())) {
                return JsonResponse.failure("手机号码错误");
            }

            String newPasswordEncrypted = DigestUtil.md5Hex(passwordUpdateDTO.getNewPassword());
            int result = userDao.updatePassword(userPO.getId(), newPasswordEncrypted);
            if (result <= 0) {
                return JsonResponse.failure("密码修改失败");
            }
            return JsonResponse.success(null, "密码修改成功");
        } catch (Exception e) {
            return JsonResponse.failure("密码修改异常：" + e.getMessage());
        }
    }


    /*根据用户名获取 UserPO 并验证状态*/
    private JsonResponse<UserPO> validateUser(String username) {
        UserPO userPO = userDao.selectByUsername(username);
        if (userPO == null) {
            return JsonResponse.failure("用户不存在");
        }
        if (userPO.getStatus() == 1) {
            return JsonResponse.failure("账号已被禁用，请联系管理员");
        }
        return JsonResponse.success(userPO);
    }

}